package com.shitou.shitoumember.service.impl;

import com.baomidou.mybatisplus.extension.api.R;
import com.google.code.kaptcha.Producer;
import com.shitou.shitoucommons.exception.RRException;
import com.shitou.shitoucommons.utils.*;
import com.shitou.shitoumember.entity.MemberEntity;
import com.shitou.shitoumember.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.shitou.shitoumember.dao.CaptchaDao;
import com.shitou.shitoumember.entity.CaptchaEntity;
import com.shitou.shitoumember.service.CaptchaService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Transactional
@Service("captchaService")
public class CaptchaServiceImpl extends ServiceImpl<CaptchaDao, CaptchaEntity> implements CaptchaService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CaptchaEntity> page = this.page(
                new Query<CaptchaEntity>().getPage(params),
                new QueryWrapper<CaptchaEntity>()
        );

        return new PageUtils(page);
    }

    @Autowired
    private Producer producer;

    @Autowired
    private MemberService memberService;


    /**
     * 2000,2001,2002
     *
     * @param uuid
     * @return
     */
    @Override
    public BufferedImage createCaptcha(String uuid) {
        // 判空校验
        if (StringUtils.isEmpty(uuid) ){
            throw new RRException("uuid不能为空");
        }
        // uuid是否重复校验,重复但是没有使用
        CaptchaEntity captchaDo = this.getOne(new QueryWrapper<CaptchaEntity>().eq("uuid", uuid));
        if ( ! (captchaDo == null)  ){
            if ( captchaDo.getExpireTime().getTime() < new Date().getTime() ){
                throw new RRException("验证码已经过期");
            }
            throw new RRException("该uuid已经用过了");
        }
        // uuid重复但是时间已经过期
        String captcha = producer.createText();
        // 创建验证码实体
        CaptchaEntity umsCaptcha = new CaptchaEntity();
        umsCaptcha.setCaptcha(captcha);
        umsCaptcha.setUuid(uuid);
        // 设置10分钟过期
        umsCaptcha.setExpireTime(DateUtils.addDateMinutes(new Date(), 10));
        this.save(umsCaptcha);
        // 返回图片
        return producer.createImage(captcha);
    }

    /**
     *
     * @param uuid
     * @param captcha
     * @return
     */
    @Override
    public boolean validate(String uuid, String captcha) {

        // 通过uuid查询验证码,, uuid出错了
        CaptchaEntity captchaDo = this.getOne(new QueryWrapper<CaptchaEntity>().eq("uuid", uuid));

        if ( captchaDo == null) {
            return false;
        }
        this.removeById(captchaDo);
        // 验证码校验
        if ( captcha.equalsIgnoreCase(captchaDo.getCaptcha()) && captchaDo.getExpireTime().getTime() > new Date().getTime()){
            return true;
        }
        // 校验出错
        return false;
    }

    /**
     * 发送邮箱
     * @param email
     * @param uuid
     * @return
     */
    @Override
    public RespBean sendEmail(String uuid, String email) {
        return send(uuid, email, false);
    }


    /**
     * 普通验证码和注册验证码
     * @param uuid
     * @param email
     * @param checkRegister 是否是注册发送的邮箱
     * @return
     */
    public RespBean send(String uuid, String email, boolean checkRegister){
        // 生成验证
        BufferedImage image = this.createCaptcha(uuid);
        // 获取验证码通过uuid
        CaptchaEntity captchaDo = this.getOne(new QueryWrapper<CaptchaEntity>().eq("uuid", uuid));
        String captcha = captchaDo.getCaptcha();

        if ( checkRegister ) {
            MemberEntity member = memberService.getOne(new QueryWrapper<MemberEntity>().eq("email", email));
            if ( member != null ){
                throw new RRException("改邮箱已经被使用了");
            }
        }

        // 发送邮箱
        Mail mail = new Mail();
        Map<String, String> map = new HashMap<>();
        map.put("title", "慕阳二手商城验证码:");
        map.put("text", captcha);
        map.put("to", email);
        mail.simpleSend(map);
        return RespBean.success();
    }

    /**
     * 验证邮箱并发送验证码
     * @param uuid
     * @param email
     * @return
     */
    @Override
    public RespBean sendCheckEmail(String uuid, String email) {
        // 通过邮箱查阅会员，如果查出才可发出验证码
        MemberEntity memberDo = memberService.getOne(new QueryWrapper<MemberEntity>()
                .eq("email", email));
        if ( memberDo == null ){
            throw new RRException("邮箱未注册账号");
        }
        return sendEmail(uuid, email);
    }

    /**
     * 邮箱验证
     *
     * @param uuid
     * @param captcha
     * @param email
     * @return
     */
    @Override
    public RespBean validateEmail(String uuid, String captcha, String email) {
        boolean b = this.validate(uuid, captcha);
        if ( b ){
            return RespBean.success();
        }
        return RespBean.error("邮箱验证失败");
    }


    /**
     * 发送注册的邮箱验证码s
     * @param uuid
     * @param email
     * @return
     */
    public RespBean sendRegisterEmail(String uuid, String email){
        return send(uuid, email, true);
    }

}
